
const { Order, OrderGoods, Commodity, ADDpay,Logistics} = require('../models/order.model');

class OrderService {
    async getOrderGoods(id) {
    
        const order_goods_records = await OrderGoods.findAll({
            where: { Order_id: id },
        });

        // 遍历每一条订单商品记录
        for (const order_goods_record of order_goods_records) {
            const { goods_id, goods_num } = order_goods_record;
            console.log(goods_id, goods_num);
            // 更新库存
            const commodity = await Commodity.findOne({
                where: { commodity_id: goods_id },
            });
            if (commodity) {
              await commodity.update(
                {
                    commodity_inventory:commodity.commodity_inventory+goods_num

                },
            );
        }}}
    async createOrder(data) {
        //创建订单写入数据库
        const { order_admin,order_name, order_id, order_price, order_status,order_phone,order_address,order_province,order_remark}=data;

        try
        {
             const order = await Order.create({
            order_admin,order_name, order_id, order_price, order_status,order_phone,order_address,order_province,order_remark
        })
        return {result:order,message:"订单创建成功"}
        
        }
        catch(error)
        {
            console.log(error);
            return null;
        }
    }
    async addOrdergoods(order_goodslist,order_id) {
        //订单商品写入数据库
        console.log(order_id);
        try {
         
            const order = await Order.findOne({
                where: { Order_id: order_id },
            })
            if (order) {
               const goodslist=[]
                for(let i=0;i<order_goodslist.length;i++){  


                const {goods_id,goods_name,goods_num}=order_goodslist[i]

                 const commodity = await Commodity.findOne({
                where: { commodity_id: goods_id },
            })
            if(commodity){
                if(commodity.commodity_status==1){
                    await commodity.update({
                        commodity_inventory:commodity.commodity_inventory-goods_num
                    })
                    }
                
            }else{
                return {result:null,message:"商品不存在"}
            }
                const order_goods = await OrderGoods.create({
                    order_id, goods_name, goods_num, goods_id
                })
                goodslist.push(order_goods)
                }
                return {result:goodslist,message:"订单商品添加成功"}
            } else {
                console.log("无该订单，无法添加订单商品");
                return null
            }
        } catch (error) {
            console.log(error);
            
            return null
        }
    }
    
    //订单编号存在查询
    async getOrderById(id) {
        try {
            const order = await Order.findOne({
                
                where: { Order_id: id },
            })
            return order
        } catch (error) {
            throw new Error(error)
        }
    }
    //订单模糊查询
    async getorders(data) {
        try {
            const whereClause = {};
            const{order_name, order_id, order_status,order_phone,order_province}=data;
             
            console.log(order_name, order_id, order_status,order_phone,order_province);

            if (order_name !== null && order_name !== '' && order_name !== undefined) {
              
              
              whereClause.order_name = {
                [Sequelize.Op.like]: `%${order_name.replace(/\s+/g, '')}%`
              };
            }
            if (order_status !== null && order_status !== '' && order_status !== undefined) {
              whereClause.order_status = 
              {
                [Sequelize.Op.like]: `%${order_status}%`
              };
            }
            if (order_phone !== null && order_phone !== '' && order_phone !== undefined) {
              whereClause.order_phone = {
                [Sequelize.Op.like]: `%${order_phone}%`
              };
            }
            if (order_province !== null && order_province !== '' && order_province !== undefined) {
              whereClause.order_province = {
                [Sequelize.Op.like]: `%${order_province.replace(/\s+/g, '')}%`
              };}
            if (order_id!== null && order_id!== '' && order_id !== undefined) {
              whereClause.order_id = {
                [Sequelize.Op.like]: `%${order_id.replace(/\s+/g, '')}%`
              };
            }
            const result = await Order.findAll({
              where: whereClause,
              include: [
                {
                  model: OrderGoods,
                  as: 'bs_order_goods',
                }
              ]
            });
            
            return {result:result,message:"订单查询成功"}

        }catch (error) {
            throw new Error(error)
        }   
    }
    //订单删除
    
    async removeOrder(id) {
        try {
            const order = await Order.destroy({
                where: { Order_id: id },
            });
    
            // 获取所有与该订单相关的商品记录
            
    
            // 删除订单的商品关联记录
            const order_goods = await OrderGoods.destroy({
                where: { Order_id: id },
            });
    
            return { result: id, message: "订单删除成功" };
        } catch (error) {
            throw new Error(error);
        }
    }


    
    //订单修改
    async updateOrder(data) {
        try {
            const { order_id, order_admin,order_name, order_price, order_status,order_phone,order_address,order_province,order_remark}=data;
            
             await Order.update({
                order_admin,order_name, order_id, order_price, order_status,order_phone,order_address,order_province,order_remark
            }, {
                where: { Order_id: order_id },
            })
            const order=await Order.findOne({
                where: { Order_id: order_id },
            })
            return {result:order,message:"订单修改成功"}
        } catch (error) {
            throw new Error(error)
        }
    } 

    async getcommoditylist() {
        try {
            const result = await Commodity.findAll({
            });
            console.log("商品列表查询成功");

            return {result:result,message:"商品列表查询成功"}
        } catch (error) {
            throw new Error(error)
        }
    }
    async Addpay(data) {
        try {
            const { order_id,pay_url,pay_id,pay_number } = data;
            const addpay = await ADDpay.create({
                order_id,pay_url,pay_id,pay_number
            }
            )
            if (addpay) {
                return { result: addpay, message: "订单创建成功" }
            } else {
                return { result: null, message: "订单创建失败" }
            }
        } catch (error) {
            throw new Error(error)
        }
    }
    async getAddpay(order_id) {
        try {
            console.log(order_id);
            const addpay = await ADDpay.findOne({
                where: { order_id: order_id },
            })
            if (addpay) {
                return { result: addpay, message: "订单创建成功" }
            } else {
                return { result: null, message: "订单创建失败" }
            }
        } catch (error) {
            throw new Error(error)  
        }
    }
    async removepay(order_id) {
        try {
            const addpay = await ADDpay.destroy({
                where: { order_id: order_id },
            })
            if (addpay) {
                return { result: order_id, message: "支付信息删除成功" }
            } else {
                return { result: null, message: "支付信息删除失败" }
            }
        } catch (error) {
            throw new Error(error)
        }
    }
      async createLogistics(data) {
    //创建物流信息写入数据库
    const { order_id, logistics_name, logistics_number, logistics_time } = data;
    try {
        const logistics = await Logistics.create({
            order_id, logistics_name, logistics_number, logistics_time
        })
        return { result: logistics, message: "物流信息创建成功" }
    } catch (error) {
        throw new Error(error)
    }
}
      async getLogistics(order_id) {
    try {
        const logistics = await Logistics.findOne({
            where: { order_id: order_id },
        })
        if (logistics) {
            return { result: logistics, message: "物流信息查询成功" }
        } else {
            return { result: null, message: "物流信息查询失败" }
        }
    } catch (error) {
        throw new Error(error)
    }
      }



  
 }

module.exports = new OrderService();